package com.intel.two.filter;

import com.intel.two.pojo.user.User;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @BelongsProject: intelligentcommunity
 * @BelongsPackage: com.intel.two.filter
 * @Author: yanhongwei
 * @CreateTime: 2022-10-18  08:50
 * @Description: TODO
 * @Version: 1.0
 */


@Component
//@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        HttpSession session = request1.getSession();


        User userLogin = (User) session.getAttribute("user");
        System.out.println("拦截登录用户"+userLogin);
        if (userLogin!=null) {
            if(!"".equals(userLogin.getAccount())&&userLogin.getAccount()!=null) {
//            放行
                chain.doFilter(request, response);
            }
        }
        response1.getWriter().write("alter('请先登录')");
        response1.sendRedirect("http://127.0.0.1:5500/login1.html");//响应
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
